package com.project;

import java.util.*;
import java.lang.*;
import static java.lang.Math.random;
/**
 *
 */
public class Admin extends ABT_System {

    /**
     * Default constructor
     */
    public Admin() {
    }

    /**
     * @return 返回
     */
    private boolean checkAdmin() {
        return logFlag != 1;
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean Adjust_flight(List<String> input) { //调整航班（添加，修改，删除）
        if (checkAdmin()) return false;
        try {
            String operation = input.getFirst();
            DB_Operator flightDB = Creat_DBOP("Flight");
            DB_Operator airlineDB = Creat_DBOP("Airline");

            return switch (operation) {
                case "addFlight" -> flightDB.add(input.subList(1, input.size()));
                case "addAirline" -> airlineDB.add(input.subList(1, input.size()));
                case "deleteAirline" -> airlineDB.delete(input.subList(1, input.size()));
                case "deleteFlight" -> flightDB.delete(input.subList(1, input.size()));
                case "modifyFlight" -> flightDB.update(input.subList(1, input.size()));
                case "modifyAirline" -> airlineDB.update(input.subList(1, input.size()));
                default -> false;
            };
        } catch (ABT_SystemException e) {
            System.err.println("数据库操作异常: " + e.getMessage());
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean Adjust_ticket(List<String> input) { //调整机票（取票）
        if (checkAdmin()) return false;
        try {
            DB_Operator ticketDB = Creat_DBOP("Ticket");
            // 输入格式：["collection", ticketId, oid, uid, seat]
            List<String> updateParams = new ArrayList<>();
            updateParams.add(input.getFirst());  // ticketId（主键）
            updateParams.add(input.get(1));  // oid
            updateParams.add(input.get(2));  // uid（用户ID，非管理员ID）
            updateParams.add(input.get(3));  // seat
            updateParams.add("1");           // 状态更新为已取票
            return ticketDB.update(updateParams);

        } catch (ABT_SystemException e) {
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public String View_orders(List<String> input) { //查看订单
        if (checkAdmin()) return null;
        try {
            DB_Operator orderDB = Creat_DBOP("Order");
            List<String> orders = orderDB.find(input);
            return String.join("\n", orders);
        } catch (ABT_SystemException e) {
            return null;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean Process_registration(List<String> input) { //处理注册账号
        if (checkAdmin()) return false;
        try {
            DB_User userDB = new DB_User();
            List<String> condition = new ArrayList<>();
            condition.add(input.getFirst());
            condition.add(input.get(1));
            condition.add(input.get(2));
            condition.add(input.get(3));
            condition.add("2");// 普通用户身份
            condition.add(input.get(4));
            return userDB.add(condition);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean Banned(List<String> input) { //封禁违规账号
        if (checkAdmin()) return false;
        try {
            DB_Operator userDB = Creat_DBOP("User");
            List<String> params = new ArrayList<>();
            params.add("is_registered=0");
            params.add("uid=" + input.getFirst());
            return userDB.update(params);
        } catch (ABT_SystemException e) {
            return false;
        }
    }

    /**
     * 处理用户改签请求（核心逻辑从User类迁移）
     * @param input 输入参数格式为 [orderId, newFid, newPosition]
     * @return 操作是否成功
     */
    public boolean Process_rescheduling(List<String> input) { //处理改签
        if (input == null || input.size() < 3) {
            System.err.println("输入数据不完整，改签需要至少 3 个参数");
            return false;
        }
        if (checkAdmin()) return false;
        try {
            String orderId = input.get(0);
            String newFid = input.get(1);
            String newPosition = input.get(2);
            String userID = input.get(3);

            // 查询原Ticket记录（从订单号获取，不依赖管理员uid）
            DB_Operator ticketDB = Creat_DBOP("Ticket");
            List<String> queryTicketParams = new ArrayList<>(List.of("oid=" + orderId, "uid=" + userID));
            List<String> originalTicket = ticketDB.find(queryTicketParams);
            if (originalTicket.isEmpty()) return false;
            String[] ticketParts = originalTicket.getFirst().split(",");
            String tid = ticketParts[0];

            // 查询原Order记录
            DB_Operator orderDB = Creat_DBOP("Order");
            List<String> queryOrderParams = new ArrayList<>(List.of("oid=" + orderId));
            List<String> originalOrder = orderDB.find(queryOrderParams);
            if (originalOrder.isEmpty()) return false;
            String[] orderParts = originalOrder.getFirst().split(",");
            String oldAid = orderParts[2];  // 原舱位ID

            // 检查新航班余票
            DB_Operator airlineDB = Creat_DBOP("Airline");
            List<String> newAirlineCond = new ArrayList<>(List.of("fid=" + newFid, "position=" + newPosition));
            List<String> newAirlineInfo = airlineDB.find(newAirlineCond);
            if (newAirlineInfo.isEmpty()) return false;
            String[] newAirlineParts = newAirlineInfo.getFirst().split(",");
            String newAid = newAirlineParts[0];
            int newRemain = Integer.parseInt(newAirlineParts[4]);
            if (newRemain <= 0) return false;

            // 更新Order记录（使用原订单中的用户ID）
            List<String> updateOrderParams = new ArrayList<>();
            updateOrderParams.add(orderId);          // oid
            updateOrderParams.add(userID);           // uid
            updateOrderParams.add(newAid);           // 新舱位ID
            updateOrderParams.add(orderParts[4]);    // 原支付金额
            updateOrderParams.add(orderParts[5]);    // 原订票状态
            boolean orderUpdateSuccess = orderDB.update(updateOrderParams);

            // 更新Ticket记录（保留原用户ID）
            List<String> updateTicketParams = new ArrayList<>();
            updateTicketParams.add(tid);             // tid
            updateTicketParams.add(orderId);         // oid
            updateTicketParams.add(userID);          // uid
            updateTicketParams.add(generateSeatNumber());  // 新座位号（随机生成逻辑保留）
            updateTicketParams.add(ticketParts[4]);  // 原状态
            boolean ticketUpdateSuccess = ticketDB.update(updateTicketParams);

            // 恢复原航班余票
            List<String> oldAirlineCond = new ArrayList<>(List.of("aid=" + oldAid));
            List<String> oldAirlineInfo = airlineDB.find(oldAirlineCond);
            if (!oldAirlineInfo.isEmpty()) {
                String[] oldAirlineParts = oldAirlineInfo.getFirst().split(",");
                int oldRemain = Integer.parseInt(oldAirlineParts[4]);
                List<String> oldUpdateParams = new ArrayList<>(Arrays.asList(
                    oldAid, oldAirlineParts[1], 
                    oldAirlineParts[2].split("-")[0], oldAirlineParts[2].split("-")[1], oldAirlineParts[2].split("-")[2],
                    oldAirlineParts[3], String.valueOf(oldRemain + 1)
                ));
                airlineDB.update(oldUpdateParams);
            }

            // 扣减新航班余票
            List<String> newUpdateParams = new ArrayList<>(Arrays.asList(
                newAid, newAirlineParts[1], 
                newAirlineParts[2].split("-")[0], newAirlineParts[2].split("-")[1], newAirlineParts[2].split("-")[2],
                newAirlineParts[3], String.valueOf(newRemain - 1)
            ));
            boolean newAirlineUpdateSuccess = airlineDB.update(newUpdateParams);

            return orderUpdateSuccess && ticketUpdateSuccess && newAirlineUpdateSuccess;
        } catch (Exception e) {
            System.err.println("改签处理异常：" + e.getMessage());
            return false;
        }
    }

    /**
     * 处理用户退票请求（核心逻辑从User类迁移）
     * @param input 输入参数格式为 [orderId]
     * @return 操作是否成功
     */
    public boolean Process_refunds(List<String> input) { //处理退票
        if (input == null || input.isEmpty()) {
            System.err.println("输入数据不能为空，退票需要订单ID");
            return false;
        }
        if (checkAdmin()) return false;
        try {
            String oid = input.getFirst();
            String uid = input.get(1);
            DB_Operator orderDB = Creat_DBOP("Order");
            DB_Operator ticketDB = Creat_DBOP("Ticket");

            // 删除关联的Ticket记录
            List<String> ticketParams = new ArrayList<>(List.of("oid=" + oid, "uid=" + uid));
            List<String> tickets = ticketDB.find(ticketParams);
            String ticketId = tickets.getFirst().split(",")[0];
            ticketDB.delete(new ArrayList<>(List.of(ticketId)));

            // 删除Order记录
            return orderDB.delete(new ArrayList<>(List.of(oid)));
        } catch (ABT_SystemException e) {
            System.err.println("退票处理异常：" + e.getMessage());
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean Flight_occupancy_rate(List<String> input) { //生成航班上座率
        if (checkAdmin()) return false;
        try {
            DB_Operator airlineDB = Creat_DBOP("Airline");
            List<String> airline = airlineDB.find(input);
            // 计算上座率逻辑（需根据实际业务实现）
            return true;
        } catch (ABT_SystemException e) {
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public List<String> Income_statements(List<String> input) { //收入报表
        if (checkAdmin()) return null;
        try {
            DB_Operator orderDB = Creat_DBOP("Order");
            return orderDB.find(input);
        } catch (ABT_SystemException e) {
            return null;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean Row_line_analysis(List<String> input) { //热门行线分析
        if (checkAdmin()) return false;
        try {
            DB_Operator flightDB = Creat_DBOP("Flight");
            List<String> flights = flightDB.find(input);
            // 热门线路分析逻辑
            return true;
        } catch (ABT_SystemException e) {
            return false;
        }
    }

    // 辅助方法：生成随机座位号（原User类中的逻辑）
    private String generateSeatNumber() {
        return String.valueOf((char) ((int) (random() * 26 + 64))) + (int) (random() * 7 + 1);
    }

    public boolean ProcessUserModification(List<String> input) { //处理用户修改
        if (checkAdmin()) return false;
        try {
            DB_Operator userDB = Creat_DBOP("User");
            return userDB.update(input);
        } catch (ABT_SystemException e) {
            return false;
        }
    }
}